package com.wangyadong.hobby.metric.gauge.lession5;

import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1817:28
 * 实时性不高
 **/
public class CacheGaugeExample {

    private static final MetricRegistry metricRegistry = new MetricRegistry();
    private static final ConsoleReporter report = ConsoleReporter.forRegistry(metricRegistry).convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS).build();

    public static void main(String[] args) throws InterruptedException {
        report.start(10, TimeUnit.SECONDS);
        metricRegistry.gauge("cached-db-size", () -> new CachedGauge<Long>(30, TimeUnit.SECONDS) {
            @Override
            protected Long loadValue() {
                return queryFromDB();
            }
        });
        System.out.println("===========" + System.currentTimeMillis());
        Thread.currentThread().join();
    }

    private static long queryFromDB() {
        System.out.println("=====queryFromDB======");
        return System.currentTimeMillis();
    }

    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(6));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
